package com.sghd.candy.module.box.manager;

import com.sghd.common.ramcache.IEntity;
import com.sghd.common.ramcache.PerPersist;
import com.sghd.common.ramcache.anno.Cached;
import com.sghd.common.ramcache.anno.CachedSizes;
import com.sghd.common.ramcache.anno.Persister;
import com.sghd.common.ramcache.anno.Persisters;
import com.sghd.common.ramcache.enhance.Enhance;
import com.sghd.common.utils.json.JsonUtils;
import com.sghd.pojo.candy.box.enums.KeyType;

import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Allen
 * @date 2018/12/13
 */
@Entity
@Table(catalog = "bsdld")
@Cached(size = CachedSizes.DEFAULT, persister = @Persister(Persisters.PRE_10_MINUTE))
public class PlayerBox implements IEntity<Long>, PerPersist {
    /**玩家Id*/
    @Id
    private Long playerId;

    /**玩家宝箱钥匙*/
    @Transient
    private Map<Integer, Integer> boxKeys;
    @Lob
    private String boxKeysJson;

    public Long getPlayerId() {
        return playerId;
    }

    void setPlayerId(Long playerId) {
        this.playerId = playerId;
    }

    public Map<Integer, Integer> getBoxKeys() {
        return boxKeys;
    }

    void setBoxKeys(Map<Integer, Integer> boxKeys) {
        this.boxKeys = boxKeys;
    }

    public String getBoxKeysJson() {
        return boxKeysJson;
    }

    void setBoxKeysJson(String boxKeysJson) {
        this.boxKeysJson = boxKeysJson;
    }

    static PlayerBox valueOf(long playerId) {
        PlayerBox playerBox = new PlayerBox();
        playerBox.setPlayerId(playerId);
        playerBox.setBoxKeys(new HashMap<>());
        return playerBox;
    }

    @Enhance
    void change(KeyType keyType, int changeNum) {
        this.boxKeys.put(keyType.ordinal(), this.boxKeys.getOrDefault(keyType.ordinal(),0) + changeNum);
    }
    @Override
    public Long getId() {
        return this.playerId;
    }

    @Override
    public void afterLoad() {
        boxKeys = JsonUtils.string2Map(boxKeysJson, Integer.class, Integer.class);
    }

    @Override
    public void beforePersist() {
        boxKeysJson = JsonUtils.object2String(boxKeys);
    }
}
